package mo.byte_school;

import java.util.Random;

public class L215 {

    private Random random = new Random();

    public int findKthLargest(int[] nums, int k) {
        return partition(nums, 0, nums.length-1, nums.length - k);
    }
    
    private int partition(int[] nums, int left, int right, int k) {
        int i = random.nextInt(right - left + 1) + left;
        swap(nums, i, right);
        int p = left - 1;
        for (int j = left; j < right; j++) {
            if (nums[j] <= nums[right]) {
                swap(nums, j, ++p);
            }
        }
        p++;
        swap(nums, p, right);
        if (p == k) {
            return nums[p];
        } else {
            return p < k ? partition(nums, p+1, right, k) : partition(nums, left, p-1, k);
        }
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
}
